package com.wd.mylibrary_live.view.activity

import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.SurfaceView
import android.widget.FrameLayout
import android.widget.Toast
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.wd.mylibrary_base.base.BaseActivity
import com.wd.mylibrary_base.bean.FindLeaderBoardBean
import com.wd.mylibrary_base.utils.MyApp
import com.wd.mylibrary_live.R
import com.wd.mylibrary_live.databinding.ActivityLiveBinding
import com.wd.mylibrary_live.viewmodel.LiveViewModel
import io.agora.rtc2.ChannelMediaOptions
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.RtcEngineConfig
import io.agora.rtc2.video.VideoCanvas

class LiveActivity : BaseActivity<LiveViewModel,ActivityLiveBinding>(R.layout.activity_live) {
     private  var mRtcEngine:RtcEngine?=null
    var  flag:Boolean=false
    var  labArr= mutableListOf<FindLeaderBoardBean.Result>()
    var  mediaPlayer:MediaPlayer= MediaPlayer()
    var  userId=MyApp.sp.getInt("userId",0)
    var  sessionId=MyApp.sp.getString("sessionId","")
    override fun initView() {
        initializeAndJoinChannel()
        val liveId = intent.getIntExtra("liveId", 0)
        val musicLinks = MyApp.sp.getString("musicLinks", "") as String
        if (musicLinks !== null && musicLinks !== "") {
            mediaPlayer.reset()
            mediaPlayer.setDataSource(musicLinks)
            mediaPlayer.prepare()
            mediaPlayer.start()

        }
        //获取主播昵称头像
        var  headPic=MyApp.sp.getString("headPic",null)
        var  nickName=MyApp.sp.getString("nickName",null)
        //设置直播主播头像
        Glide.with(this).load(headPic)
            .circleCrop()
            .into(dataBinding.livePlayUserPicId)
        //设置主播昵称
        dataBinding.livePlayUserNameId.setText(nickName)
        if (liveId!=null){
            viewModel.liveId=liveId
        }

        viewModel.agoraToken= MyApp.sp.getString("agoraToken","").toString()
        viewModel.compositeWsUrl=MyApp.sp.getString("compositeWsUrl","").toString()
        viewModel.channelName=MyApp.sp.getString("channelName","").toString()

//        viewModel.agoraToken= MMKVUtil.getAgoraToken()
//        viewModel.compositeWsUrl=MMKVUtil.getCompositeWsUrl()
//        viewModel.channelName=MMKVUtil.getChannelName()

//        viewModel.connectSocket(this)
        //关闭直播
        dataBinding.deleteLiveActivityId.setOnClickListener {
            viewModel.closeLive(userId,sessionId.toString())
        }
        viewModel.closeLiveData.observe(this, Observer {
            Toast.makeText(this@LiveActivity, it.message, Toast.LENGTH_SHORT).show()
            if (it.status.equals("0000")){
                finish()
            }
        })


    }
        override fun dataObserve() {

        }

        //初始化推流，加入频道
        private fun initializeAndJoinChannel() {
            try {
                //创建RtcEngineConfig对象,并进行配置
                val config = RtcEngineConfig()
                config.mContext = baseContext
                config.mAppId = "e394d3be4df34e1d9f8b67bc5a007de7"
                config.mEventHandler = object : IRtcEngineEventHandler() {
                    override fun onUserJoined(uid: Int, elapsed: Int) {
                        runOnUiThread {
                            setupRemoteVideo(uid)
                        }
                    }

                    //加入成功回调
                    override fun onJoinChannelSuccess(channel: String?, uid: Int, elapsed: Int) {
                        super.onJoinChannelSuccess(channel, uid, elapsed)
                        //推流
                        viewModel.startPushStream(userId , sessionId.toString(), viewModel.liveId)
                    }

                    //远端用户或主播离开当前频道回调
                    override fun onUserOffline(uid: Int, reason: Int) {
                        super.onUserOffline(uid, reason)
                        com.blankj.utilcode.util.ThreadUtils.runOnUiThread {
                            Toast.makeText(
                                this@LiveActivity,
                                "User offline: $uid",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                }
                //创建并初始化
                mRtcEngine = RtcEngine.create(config)
            } catch (e: Exception) {
                throw RuntimeException("Check the error.")
            }
            //启用视频模块
            mRtcEngine?.enableAudio()
            //开启本地预览
            mRtcEngine?.startPreview()
            // 创建一个 SurfaceView 对象，并将其作为 FrameLayout 的子对象
            val container = findViewById<FrameLayout>(R.id.local_video_view_container2)
            val surfaceView = SurfaceView(baseContext)
            container.addView(surfaceView)
            // 将 SurfaceView 对象传入声网实时互动 SDK，设置本地视图
            mRtcEngine?.setupLocalVideo(
                VideoCanvas(
                    surfaceView,
                    VideoCanvas.RENDER_MODE_FIT,
                    3840
                )
            )
            // 创建 ChannelMediaOptions 对象，并进行配置
            val options = ChannelMediaOptions()
            // 根据场景将用户角色设置为 BROADCASTER (主播) 或 AUDIENCE (观众)
            options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER
            // 直播场景下，设置频道场景为 BROADCASTING (直播场景)
            options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING
            // 使用临时 Token 加入频道，自行指定用户 ID 并确保其在频道内的唯一性
            mRtcEngine?.joinChannel(
                viewModel.agoraToken, viewModel.channelName, 3840,
                options
            )
        }
    //设置视图
    private fun setupRemoteVideo(uid:Int){
        val container=findViewById<FrameLayout>(R.id.remote_video_view_container2)
        val surfaceView=SurfaceView(baseContext)
        surfaceView.setZOrderMediaOverlay(true)
        container.addView(surfaceView)
        mRtcEngine!!.setupRemoteVideo(
            VideoCanvas(
                surfaceView,
                VideoCanvas.RENDER_MODE_FIT,
                uid
            )
        )
    }

}